package com.bw.module_service.ui

import android.annotation.SuppressLint
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.appContext
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.lib_storage.mmkv.AuthMMKV
import com.bw.module_service.R
import com.bw.module_service.databinding.ActivityAttendancesBinding
import com.bw.module_service.utils.ToastUtils
import com.bw.module_service.viewmodel.ServiceViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Locale

@AndroidEntryPoint
@Route(path = Router.Ui.AttendancesActivity)
class AttendancesActivity : BaseActivity<ServiceViewModel,ActivityAttendancesBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_attendances

    private val handler = Handler(Looper.getMainLooper())

    private val mViewModel:ServiceViewModel by viewModels()

    private var status = ""

    val kv = MMKV.defaultMMKV()


    override fun initView() {
        super.initView()

        val calendar = Calendar.getInstance()

        handler.postDelayed(timeRunnable, 0)

        val timeFormat2 = SimpleDateFormat("yyyy年MM月dd日 E",Locale.getDefault())
        val format2Result = timeFormat2.format(calendar.time)
        val chineseFormat2Result = format2Result.replace("Mon", "星期一")
            .replace("Tue", "星期二")
            .replace("Wed", "星期三")
            .replace("Thu", "星期四")
            .replace("Fri", "星期五")
            .replace("Sat", "星期六")
            .replace("Sun", "星期日")
        mBinding.current.text = chineseFormat2Result
    }


    @SuppressLint("SuspiciousIndentation")
    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
        mBinding.back.setOnClickListener {
            finish()
        }
        val currentDate = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
        val signInTime = kv.decodeString("login", "")
        val signOutTime = kv.decodeString("loginOut", "")

        // 1. 判断今天是否已上班打卡
        val hasSignIn = !TextUtils.isEmpty(signInTime) && signInTime?.substring(0, 10) == currentDate
        // 2. 判断今天是否已下班打卡
        val hasSignOut = !TextUtils.isEmpty(signOutTime) && signOutTime?.substring(0, 10) == currentDate

        when {
            hasSignOut -> {
                mBinding.sign.text = "已下班打卡"
                mBinding.sign.isEnabled = false
                mBinding.a1.text = "已下班打卡"
                mBinding.a1.isEnabled = false
            }

            hasSignIn -> {
                mBinding.sign.text = "下班打卡"
            }

            else -> {
                mBinding.sign.text = "上班打卡"
            }
        }

        mBinding.sign.setOnClickListener {
            if(AuthMMKV.token==""){
                ToastUtils.showLong(appContext,"请先登录")
                ARouter.getInstance().build(Router.Ui.LoginActivity).navigation()
                return@setOnClickListener
            }
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
            val workTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            val workStart = LocalTime.of(8, 0) //上班时间
            if(mBinding.sign.text == "上班打卡"){
                kv.encode("login", time)
                Log.d("clbb","上班打卡：$time")
                if(LocalTime.parse(workTime).isAfter(workStart)){
                    status = "迟到"
                }else{
                    status = "正常"
                }
                mBinding.sign.text = "下班打卡"


            }else{
                kv.encode("loginOut", time)
                val workEnd = LocalTime.of(17,0)
                if(LocalTime.parse(workTime).isBefore(workEnd)){
                    status = "早退"
                }else{
                    status = "正常"
                    mBinding.sign.isEnabled = false
                }
            }





            val login = kv.decodeString("login","").toString()
            Log.d("clbb","上班时间：$login")
            val loginOut =  kv.decodeString("loginOut","").toString()
            Log.d("clbb","下班时间：$loginOut")


            val map = mapOf(
                "userId" to 0,
                "afternoonCheckIn" to loginOut,
                "currentLocation" to "lat,lon",
                "id" to 0,
                "location" to "天津八维培训",
                "morningCheckIn" to login,
                "status" to status,
                "userId" to 1
            )
            mViewModel.getSign(map)
        }

        val login = kv.decodeString("login","").toString()
            mBinding.a1.setOnClickListener{

                if(login != ""){
                    val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                    val workTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())

                    kv.encode("loginOut", time)
                    val workEnd = LocalTime.of(17,0)
                    if(LocalTime.parse(workTime).isBefore(workEnd)){
                        status = "早退"
                    }else{
                        status = "正常"
                        mBinding.sign.isEnabled = false
                    }

                    val login = kv.decodeString("login","").toString()
                    Log.d("clbb","上班时间：$login")
                    val loginOut =  kv.decodeString("loginOut","").toString()
                    Log.d("clbb","下班时间：$loginOut")


                    val map = mapOf(
                        "userId" to 0,
                        "afternoonCheckIn" to loginOut,
                        "currentLocation" to "lat,lon",
                        "id" to 0,
                        "location" to "天津八维培训",
                        "morningCheckIn" to login,
                        "status" to status,
                        "userId" to 1
                    )
                    mViewModel.getSign(map)
                }else{
                    ToastUtils.showLong(this,"请先完成上班打卡")
                    return@setOnClickListener
                }
            }




    }

    private val timeRunnable = object : Runnable {
        @RequiresApi(Build.VERSION_CODES.O)
        override fun run() {
            mBinding.currentTime.text = LocalDateTime.now().format(
                DateTimeFormatter.ofPattern("HH:mm:ss", Locale.getDefault())
            )
            handler.postDelayed(this, 1000)
        }
    }

    override fun initListener() {
        mViewModel.getSign_.observe(this){
            ToastUtils.showLong(this,"签到成功")
            finish()
        }
    }



}